/**
 * 简单路由组件 - 替代react-router-dom
 * 提供基本的路由功能
 */
import React, { createContext, useContext, useState, ReactNode } from 'react';

interface RouteContextType {
  currentPath: string;
  navigate: (path: string) => void;
}

const RouteContext = createContext<RouteContextType | undefined>(undefined);

/**
 * 路由提供者组件
 */
export const Router: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [currentPath, setCurrentPath] = useState(window.location.hash.slice(1) || '/');

  /**
   * 导航到指定路径
   */
  const navigate = (path: string) => {
    setCurrentPath(path);
    window.location.hash = path;
  };

  return (
    <RouteContext.Provider value={{ currentPath, navigate }}>
      {children}
    </RouteContext.Provider>
  );
};

/**
 * 路由钩子
 */
export const useRouter = () => {
  const context = useContext(RouteContext);
  if (!context) {
    throw new Error('useRouter must be used within a Router');
  }
  return context;
};

/**
 * 路由组件
 */
export const Routes: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { currentPath } = useRouter();
  
  const routes = React.Children.toArray(children) as React.ReactElement[];
  
  for (const route of routes) {
    if (route.props.path === currentPath) {
      return route.props.element;
    }
  }
  
  // 默认返回第一个路由
  return routes[0]?.props.element || null;
};

/**
 * 路由项组件
 */
export const Route: React.FC<{ path: string; element: ReactNode }> = () => {
  return null; // 这个组件不直接渲染
};

/**
 * 导航链接组件
 */
export const Link: React.FC<{ to: string; children: ReactNode; className?: string }> = ({ to, children, className }) => {
  const { navigate } = useRouter();
  
  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    navigate(to);
  };
  
  return (
    <a href={`#${to}`} onClick={handleClick} className={className}>
      {children}
    </a>
  );
};